/**
 * Manage image caching within a set
 * @param {Set} set
 * @constructor
 */
function ImageCache(set)
{
	/** @type {Array.<Number>} */
	var _indices = [];
	/** @type {Number} */
	var _timer = 0;

	/**
	 * Begin pre-loading images
	 */
	this.load = function()
	{
		window.clearTimeout(_timer);
		_indices = [set.photoIndex];
		calculateRange();               // calculate range of photos to preload
		loadNext();
	};

	function loadNext()
	{
		if (_indices.length > 1)
		{
			if (set.photos[parseInt(_indices.shift())].download())
			{
				_timer = window.setTimeout(loadNext, Enum.duration.betweenDownloads);
			}
			else
			{
				loadNext();     // no download because already loaded — immediately load next
			}
		}
	}

	/**
	 * Create an ordered list of photo IDs increasingly distant (back and forwards)
	 * from the current index
	 */
	function calculateRange()
	{
		var max = Enum.photoPreloadMax;
		var start = set.photoIndex - (max / 2);
		var end = set.photoIndex + (max / 2);

		if (start < 0) { end += Math.abs(start); start = 0; }
		if (end >= set.total) { start -= (set.total - end); end = set.total - 1; }
		if (start < 0) { start = 0; }

		for (var f = set.photoIndex + 1, b = set.photoIndex - 1, i = 1; i <= max; f++, b--, i++)
		{
			if (f <= end)   _indices.push(f);
			if (b >= start) _indices.push(b);
		}
	}
}